﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Frame.Lib.Web
{
    /// <summary>
    /// 此类为MVC或轻量级下翻页使用，不支持ViewState
    /// </summary>
    public class PagerSetting
    {
        public PagerSetting()
        {
            PageSize = 20;
            PageIndex = 1;
        }

        /// <summary>
        /// 每页的大小
        /// </summary>
        public int PageSize
        {
            get;
            set;
        }

        /// <summary>
        /// 当前页码，从1开始编号
        /// </summary>
        public int PageIndex
        {
            get;
            set;
        }


        private int _recordCount;
        /// <summary>
        /// 总记录数
        /// </summary>
        public int RecordCount
        {
            get
            {
                return _recordCount;
            }
            set
            {
                _recordCount = value;

                if (value <= (PageIndex - 1) * PageSize)
                {
                    PageIndex = value / PageSize;
                    if (value % PageSize > 0)
                    {
                        PageIndex++;
                    }
                }
            }
        }

        public int SkipCount
        {
            get
            {
                return (PageIndex - 1) * PageSize;
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        public string OrderBy
        {
            get;
            set;
        }

        /// <summary>
        /// 条件
        /// </summary>
        public string Where
        {
            get;
            set;
        }


        public string GetPagerSql(string select)
        {
            string where = "1=1";
            if (!string.IsNullOrEmpty(this.Where))
            {
                where = this.Where;
            }

            string orderby = "ID";
            if (!string.IsNullOrEmpty(this.OrderBy))
            {
                orderby = this.OrderBy;
            }

            string sql = select.ToLower().Trim();
            //去掉开头的select
            if (sql.StartsWith("select"))
            {
                sql = sql.Substring(6);
            }

            if (this.PageSize == int.MaxValue)
            {
                sql = "select " + sql + " where  " + where + " order by " + orderby;
            }
            else
            {
                int begin = (this.PageIndex - 1) * this.PageSize + 1;
                int end = begin + this.PageSize - 1;
                sql = "select * from (select (row_number() over (order by " + orderby + ")) as RowID, " + sql + " where " + where + ") as tmp where RowID between " + begin + " and " + end;
            }
            return sql;
        }
    }
}
